<template>
  <div class="bar-chart">
    <div class="header" @click.stop>
      <div class="title">
        <div class="title-icon"></div>
        <div class="title-text" v-if="title">{{ title }}</div>
      </div>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script>
import data from 'china-area-data'
import * as echarts from 'echarts'

export default {
  name: 'BiBarChart',
  props: {
    title: {
      type: String,
      default: ''
    },
    chartData: {
      type: Object,
      required: true,
      default: () => ({
        xAxis: ['品牌A', '品牌B', '品牌C', '品牌D', '品牌E', '品牌F', '品牌G', '品牌H'],
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: [320, 302, 301, 334, 390, 330, 320, 332]
          }
        ]
      })
    },
    options: {
      type: Object,
      default: () => ({})
    },
    unit: {
      type: String,
      default: "元"
    }
  },
  data() {
    return {
      chart: null,
      chartOptions: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          top: '6%',
          left: '0%',
          right: '4%',
          bottom: '18%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            // interval: 0,
            // rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: []
      }
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.$nextTick(() => {
          console.log(val, "chartDatachartData")
          this.updateChart()
        })
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    initChart() {
      if (!this.$refs.chartRef) {
        console.warn('柱状图容器未找到')
        return
      }

      try {
        this.chart = echarts.init(this.$refs.chartRef)
        this.updateChart()

        // 添加点击事件监听
        this.chart.on('click', (params) => {
          this.$emit('bar-click', {
            name: params.name,
            value: params.value,
            index: params.dataIndex
          })
        })
      } catch (error) {
        console.error('初始化柱状图失败:', error)
      }
    },
    updateChart() {
      if (!this.chart) return
      const _this = this
      const options = {
        ...this.chartOptions,
        grid:{
          top:  '10%',
          left: '1%',
          right: '4.2%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          ...this.chartOptions.xAxis,
          data: this.chartData.xAxis,
          axisLabel: {
            formatter: (params) => {
              let maxLength = 4
              return params.replace(new RegExp(`(.{${maxLength}})`, 'g'), '$1\n')
              .replace(/\n$/, ''); // 去除末尾多余的换行符
            }
          }
        },
        // series: this.chartData.series
        series: [{
          data: this.chartData.series,
          itemStyle: {
            color: '#EA1111',
          },
          label: {
            show: true,
            position: 'top',
            formatter: function (params) {
              let value = params.data;
              if (value < 1 && value > -1) {
                return `${value.toFixed(1).replace(/\.0$/, '')}${ _this.title !== '区域库销比' ? _this.unit : ''}`;
              }
              if (value < 10000 && value > -10000) {
                return `${value.toFixed(1).replace(/\.0$/, '')}${_this.title !== '区域库销比' ? _this.unit : ''}`;
              }
              else if (value < 100000000 && value > -100000000) {
               return value < 0 ? `${~~(value / 10000)}万${_this.unit}` : `${~~(value / 10000)}万${_this.title !== '区域库销比' ? _this.unit : ''}`;
              }
              else {
              return value < 0 ? `${~~(value / 100000000)}亿${_this.unit}` : `${~~(value / 100000000)}亿${_this.title !== '区域库销比' ? _this.unit : ''}`;
              }
            }
            // formatter: (params) => {
            //   let value = params.data;
            //   if (value < 1 && value > -1) {
            //     return `${value.toFixed(1)}${this.title !== '区域库销比' ? _this.unit : ''}`;
            //   } else if (value < 10000 && value > -10000) {
            //     return `${~~value}${this.title !== '区域库销比' ? _this.unit : ''}`;
            //   } else if (value < 100000000 && value > -100000000) {
            //     return value < 0 ? `${~~(value / 10000)}万${_this.unit}` : `${~~(value / 10000)}万${this.title !== '区域库销比' ? _this.unit : ''}`;
            //   } else {
            //     return value < 0 ? `${~~(value / 100000000)}亿${_this.unit}` : `${~~(value / 100000000)}亿${this.title !== '区域库销比' ? _this.unit : ''}`;
            //   }
            // }
          },
          type: 'bar',
          // barWidth: '50',
          barMaxWidth: '80',
          barMinWidth: '5'
        }],
        yAxis: {
          type: "value",
          axisLabel: {
            show: true,
            formatter: (params) => {
              let value = params;
              if (value < 1 && value > -1) {
                return `${value.toFixed(1).replace(/\.0$/, '')}${this.title !== '区域库销比' ? _this.unit : ''}`;
              }
              if (value < 10000 && value > -10000) {
                return `${value.toFixed(1).replace(/\.0$/, '')}${this.title !== '区域库销比' ? _this.unit : ''}`;
              }
              else if (value < 100000000 && value > -100000000) {
                const formattedValue = ~~(Math.abs(value) / 10000);
                return `${value < 0 ? '-' : ''}${formattedValue}万${this.title !== '区域库销比' ? _this.unit : ''}`;
              }
              else {
                const formattedValue = ~~(Math.abs(value) / 100000000);
                return `${value < 0 ? '-' : ''}${formattedValue}亿${this.title !== '区域库销比' ? _this.unit : ''}`;
              }
            }
          },
        },
        dataZoom: [{
          type: 'inside',
          xAxisIndex: [0],
          start: 0,
          end: 100,
          minValueSpan: 7,
          maxValueSpan: 12,
          height: 20,
          bottom: 0,
          borderColor: 'transparent',
          backgroundColor: '#e2e2e2',
          fillerColor: 'rgba(167,183,204,0.4)',
          handleStyle: {
            color: '#fff',
            borderColor: '#ACB8D1'
          },
          textStyle: {
            color: '#333'
          },
          zoomOnMouseWheel: true,  // 启用鼠标滚轮缩放
          moveOnMouseMove: true,   // 启用鼠标移动平移
          moveOnMouseWheel: false, // 禁用鼠标滚轮平移
          preventDefaultMouseMove: true,  // 阻止默认的鼠标移动行为
        }],
      }
      this.chart.setOption(options)
    },
    resetChart() {
      if (this.chart) {
        this.chart.dispose();
        this.chart = null;
        this.$nextTick(() => {
          console.log('数据格式化');
          this.initChart();
        });
      }
    },
    handleResize() {
      this.chart && this.chart.resize()
    }
  }
}
</script>

<style lang="scss" scoped>
.bar-chart {
  width: 100%;
  height: 100%;
  padding: 0 10px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 54px;
  }

  .title {
    display: flex;
    align-items: center;
  }

  .title-text {
    font-weight: 500;
    font-size: 20px;
    color: #333333;
    margin: 0 0 0 6px;
  }

  .title-icon {
    width: 20px;
    height: 20px;
    background-color: #000;
    border-radius: 50%;
    background: url('../../../assets/BI/icon.png') no-repeat center center;
    background-size: 100% 100%;
  }

  .chart {
    height: calc(100% - 50px);
  }
}
</style>